package createThread.secSkill;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;


/**
 * @author wang'ji'cheng
 * @date 2025/7/28
 */
public  class SecSkill {
    static int stock = 100;
    private static final ReentrantLock lock = new ReentrantLock();
    public static void secKill(int n) throws InterruptedException {
        lock.lock();
        try {
            if(stock>=n){
                Thread.sleep(100);
                stock -=n;
                System.out.println(Thread.currentThread().getName()+"扣减成功"+"扣除"+n);
            }else {
                System.out.println(Thread.currentThread().getName() + "扣减失败");
            }
        } finally {
            lock.unlock();
        }

    }
    public static void main(String[] args) throws InterruptedException {
        //创建一个线程池
        ExecutorService executor = Executors.newFixedThreadPool(10);
        //定义计数器
        int threadCount = 200;
        CountDownLatch countDownLatch = new CountDownLatch(threadCount);
        //循环提交任务
        for (int i = 0; i < threadCount ; i++) {
            executor.submit(()->{
                try {
                    SecSkill.secKill(5);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    countDownLatch.countDown();
                }
            });
        }
        countDownLatch.await();
        executor.shutdown();
    }
}
